# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     pdf_split                |
|Author:        WYT                      |
|date:          2020/6/8                 |
 ----------------------------------------
|  Change Activity:                      |
|                  2020/6/8:             |
 ----------------------------------------
"""
import os
# import threading

from PyPDF2 import PdfFileReader, PdfFileWriter

# from util.Logger import Logger
from util.OSS import OSS
from util.pdfSplit import g
from util.pdfSplit.compress_pdf import CompressPdf, CompressPdfWithG
from util.pdfSplit.get_catalogue import get_catalogue
from util.pdfSplit.pdf_to_image import pdf_to_image
from settings import web_type as webType, site_type, materials_path, log_path, web_type, base_path, oss_id, oss_secret, \
    oss_endpoint


class thisClass():
    reader = None
    number_of_pages = None
    actualNumber = 0

    lib = None

    # dll_path = "{}/util/DEbenuPDFLibraryDLL1711.dll".format(base_path)

    @classmethod
    def clear_var(cls):
        cls.reader = None
        cls.number_of_pages = None
        cls.actualNumber = 0
        cls.lib = None
        # cls.dll_path = "{}/util/DEbenuPDFLibraryDLL1711.dll".format(base_path)



def split_pdf(infile, out_path, startPage, endPage, filename):
    # print("-----------------------------------------")
    # try:
    # :param infile: 待拆分的pdf文件 无法读取其他媒体，只能读文字
    # :param out_path: 拆分成单页的pdf文件的存储路径
    # :return: 无  banben 3.6.0

    # TODO 这里 读文件时 耗时长 可以使用 class 封装之后只读一次， 减少 文件读取次数， 减少拆分时间
    reader = thisClass.reader
    if not reader:
        reader = PdfFileReader(infile, strict=False)
        thisClass.reader = reader
    if not thisClass.number_of_pages:
        thisClass.number_of_pages = reader.getNumPages()  # 计算此PDF文件中的总页数

    # PyPDF2可以创建一个新的PDF文件，但是不能将任何文本写入到PDF。其写入PDF的能力，仅限于从其他PDF中拷贝页面、旋转页面、重叠页面和加密文件
    # 开始要大于0 结束要要小于等于总也数
    if (startPage < 1 or endPage > thisClass.number_of_pages):
        g.logger.error("file_name: {} 目录错误或pdf文件缺少---开始页：{};截止页：{}, 总页数: {}"
                       .format(filename, startPage, endPage, thisClass.number_of_pages))
        return
    else:
        out_file_name = out_path + "/" + filename + '.pdf.pdf'
        try:
            writer = PdfFileWriter()
            for i in range(startPage - 1, endPage):
                # 将文档指定页的读入到新的文档
                writer.addPage(reader.getPage(i))
            with open(out_file_name, 'wb') as outfile:
                writer.write(outfile)
            thisClass.actualNumber += 1
        except Exception as err:
            print("{} pypdf2 拆分异常, err: {}".format(out_file_name, err))

            return False

        return out_file_name

def get_file_oss(oss_path:str=None, local_path=None):
    if not oss_path or not local_path:
        return None
    path, filename = os.path.split(local_path)
    if not os.path.exists(path):
        os.makedirs(path)
    bucket_name, bucket_path = oss_path.split(":")
    oss = OSS(AccessKeyID=oss_id, AccessKeySecret=oss_secret, EndPoint=oss_endpoint, BucketName=bucket_name)
    path = oss.get_file_by_stream(object_name=bucket_path, local_path=local_path)
    return path


# class Split(threading.Thread):
class Split():
    multiple_list = {'ip': "ipr_id", 'rd': "rd_id", "ps": "ps_id", 'sta': "id", 'std': "id"}

    def __init__(self, pdf_way, pdf_save_way, co_id, year, web_type):
        super().__init__()
        self.co_id = co_id
        self.year = year
        self.pdf_way = pdf_way
        self.pdf_save_way = pdf_save_way
        self.web_type = web_type if web_type != None else webType
        self.catalogues = get_catalogue(co_id=self.co_id, year=self.year, web_type=self.web_type)()
        self.relativePath = '/{}_{}/{}/{}_{}'.format(site_type, self.year, self.web_type, site_type,
                                                     self.co_id)

    def parse_code(self, res_code=None):
        if type(res_code) == str:
            res_code = int(res_code)
        if res_code == -1:
            return str(int(self.year) + res_code)
        elif res_code == -2:
            return str(int(self.year) + res_code)
        elif res_code == -3:
            return str(int(self.year) + res_code)
        else:
            return str(res_code)

    def run(self):
        try:
            g.logger.info("获取目录条数: {}".format(len(self.catalogues)))
            # print(self.catalogues)
            # print(self.catalogues)
            for index, i in enumerate(self.catalogues, 1):
                resType = i.get('type')
                treeParentid = i.get("parent_id")
                resName = i.get("res_name")
                resCode = i.get('calculate')
                # TODO 取某些附件使用
                # if resType != "ip":
                #     continue
                # if self.pdf_save_way.endswith(self.relativePath):
                #     pass
                # else:
                #     self.pdf_save_way += self.relativePath
                # print(i)
                if resType in self.multiple_list or treeParentid or resCode:
                    out_path = self.pdf_save_way + '/' + resType.upper()
                else:
                    out_path = self.pdf_save_way
                startPage = i["file_start"]
                endPage = i["file_end"]
                if resType in self.multiple_list:
                    filename = resType + "_" + str(i.get(self.multiple_list.get(resType))).zfill(2)
                elif treeParentid or resCode:
                    filename = resType + '_' + self.parse_code(res_code=resCode)
                else:
                    filename = resType
                # 　TODO 这里 为 i 的 filePath 赋值 为 out_path - self.pdfSaveWay + filename + '.pdf'
                oss_path = i.get("oss_path")
                # pdf 文件路径
                if not os.path.exists(out_path):
                    os.makedirs(out_path)
                _pa = out_path + "/" + filename + '.pdf'
                if resType == "buslic" and self.web_type == "ctp":
                    # pdf 转化的图片的路径
                    __pa = out_path + "/" + "buslic.png"
                    if os.path.isfile(__pa):
                        if os.path.getsize(__pa) / 1024 / 1024 < float(i.get("size")):
                            continue
                    # TODO 这里调用 转换pdf为图片的方法
                    # if not i.get("oss_path"):
                    filePath = None
                    if oss_path:
                        filePath = get_file_oss(oss_path=oss_path, local_path=_pa)
                        # 从 oss 中 取出 文件 并 放到 filePath 中
                    try:
                        out_filename = pdf_to_image(imagePath=out_path,
                                                    filename=filename, size=0.48, filePath=filePath)
                    except Exception as err:
                        pass
                    thisClass.actualNumber += 1
                else:
                    if os.path.isfile(_pa):
                        if os.path.getsize(_pa) / 1024 / 1024 < float(i.get("size")):
                            continue
                    out_filename = None
                    if oss_path:
                        # 从 oss 中读取 文件
                        out_filename = get_file_oss(oss_path=oss_path, local_path=_pa + ".pdf")
                    else:
                        continue
                    if not os.path.getsize(_pa + ".pdf"):
                        os.remove(_pa + ".pdf")
                        continue
                    # 判断是否存在
                    # if not oss_path and not out_filename:
                    #     out_filename = split_pdf(self.pdf_way, out_path, startPage, endPage, filename)
                    #     if out_filename is False:
                    #         continue
                    # try:
                    CompressPdf(file_path=out_filename, max_size=i.get("size"), web_type=self.web_type).compress()
                    # except Exception as err:
                    #     print("压缩异常:", err)
                    # CompressPdfWithG(file_path=out_filename, max_size=i.get("size"), web_type=self.web_type).compress()

                print("out_filename:", out_filename)
        except Exception as err:
            err_msg = "{} file:{} lines:{}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error("压缩附件异常: {} -- {}".format(self.co_id, err_msg))



if __name__ == '__main__':
    # g.logger = Logger(log_file_name=log_path, log_level=Logger.DEBUG,
    #                   logger_name="autoflow_{}.log".format(web_type)).get_log()
    # # Split(pdf_way="C:\\Users\\Administrator\\Desktop\\测试用.pdf", pdf_save_way=materials_path, co_id=307566, year=2020, web_type=webType).start()
    # Split(pdf_way="C:\\Users\\Administrator\\Desktop\\测试用.pdf", pdf_save_way=materials_path.replace("materials", "compressless"), co_id=307566, year=2020, web_type=webType).start()

    file_name = "GR20203724290"
    object_name="{}.pdf".format(file_name)
    local_path="C:\\Users\\Administrator\\Desktop\\Project\\autoflow\\original_files\\{}.pdf".format(file_name)

    # reader = PdfFileReader(local_path)
    # print(reader.getNumPages())
    pass

